package com.fatdetection.demo.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fatdetection.demo.bean.Record;
import com.fatdetection.demo.mapper.RecordMapper;
import com.fatdetection.demo.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class RecordServiceImp implements RecordService {

    @Autowired
    RecordMapper recordMapper;

    @Override
    public Record getRecord(String phone, String partName) {
        return recordMapper.selectList(new QueryWrapper<Record>()
                .eq("phone", phone)
                .eq("part_name", partName)
        .like("last_time", new SimpleDateFormat("yyyy-MM-dd").format(new Date())).orderByDesc("last_time")).get(0);
    }

    @Override
    public Boolean insertRecord(Record record) {
        if(record != null){
            int count =  recordMapper.insert(record);
            return count > 0;
        }
       return false;
    }

    @Override
    public Boolean delRecord(Integer id) {
        return recordMapper.delete(new QueryWrapper<Record>().eq("record_id", id)) == 1;
    }

    @Override
    public Boolean updateRecord(Record record) {
        return recordMapper.update(record, new UpdateWrapper<Record>().eq("record_id", record.getRecordId())) == 1;
    }

    @Override
    public List<Record> findAll() {
        return recordMapper.selectList(null);
    }

    @Override
    public List<Record> findByPart(String partName) {
        return recordMapper.selectList(new QueryWrapper<Record>().eq("part_name", partName));
    }

    @Override
        public List<Record> findByStuId(String stuId) {
        return recordMapper.selectList(new QueryWrapper<Record>().eq("phone", stuId));
    }

    @Override
    public List<Record> findByCtime(Date startT, Date endT, String partName, String userId) {
        Date date = new Date(endT.getTime() + 24 * 3600 * 1000);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(date);
        return recordMapper.selectList(new QueryWrapper<Record>()
                .ge("create_time", startT)
                .le("create_time", format)
                .and((e)->{
                    e.eq("part_name", partName).eq("phone", userId);
                }));
    }
}
